package com.zxx.coolweather._wuguan3_ok;

import org.litepal.util.LogUtil;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 自动刷新Token的拦截器
 *
 * OkHttpClient.Builder().addInterceptor(new TokenInterceptor())
 *
 * @author zxx on 2022/1/13
 */
public class TokenInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);

        //根据和服务端的约定判断token过期
        if (isTokenExpired(response)) {
            //同步请求方式，获取最新的token
            //String newSession = getNewToken();

            //使用新的Token，创建新的请求
            Request newRequest = chain.request()
                    .newBuilder()
                    .header("Cookie", "JSESSIONID=" + "newSession")
                    .build();

            //重新请求
            return chain.proceed(newRequest);
        }
        return response;
    }

    //同步请求方式，获取最新的Token
    //private String getNewToken() {
        // 通过一个特定的接口获取新的token，此处要用到同步的retrofit请求
        //保存到了本地
        //Response_Login loginInfo = CacheManager.restoreLoginInfo(BaseApplication.getContext());
        //String username = loginInfo.getUserName();
        //String password = loginInfo.getPassword();
        //网络请求
        //Call<Response_Login> call = WebHelper.getSyncInterface().synclogin(new Request_Login(username, password));
        //loginInfo = call.execute().body();
        //LogUtil.print("loginInfo=" + loginInfo.toString());
        //保存
        //loginInfo.setPassword(password);
        //CacheManager.saveLoginInfo(loginInfo);
        //return loginInfo.getSession();
    //}

    //根据Response，判断Token是否失效
    private boolean isTokenExpired(Response response) {
        if (response.code() == 404) {
            return true;
        }
        return false;
    }
}
